package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
@Topic("task/" + TopicConfig.VMS_STATUS_TOPIC)
public class VMStatusHandler implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) throws IOException {
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        if (vmStatusContract == null || vmStatusContract.getStatusInfo() == null){
            throw new LogicException("设备状态自检异常");
        }
        List<StatusInfo> statusInfos = vmStatusContract.getStatusInfo();
//        for (StatusInfo statusInfo : statusInfos) {
//            if (!statusInfo.isStatus()){
//
//            }
//        }
        if (statusInfos.stream().anyMatch(statusInfo -> statusInfo.isStatus() == false )){
            //根据售货机编号查询售货机
            VmVO vmInfo = vmService.getVMInfo(vmStatusContract.getInnerCode());
            //根据点位Id查询工单数最少的员工
            int userId = taskService.getLeastUser(vmInfo.getRegionId(), true);
            //封装工单对象
            TaskViewModel taskViewModel = new TaskViewModel();
            taskViewModel.setUserId(userId);
            taskViewModel.setInnerCode(vmStatusContract.getInnerCode());
            taskViewModel.setCreateType(0);
            taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);
            taskViewModel.setDesc("自动维修工单");
            taskService.create(taskViewModel);
        }
    }
}
